package network

import (
	"github.com/sirupsen/logrus"
	"net"
)

type ConnSet map[net.Conn]struct{}

type TcpSession struct {
	conn       net.Conn    //连接对象
	writeQueue chan []byte //写消息的channel
	closeFlag  bool        //关闭标记

}

func newTcpSession(conn net.Conn, writeQueueSize int) *TcpSession {
	tcpSession := new(TcpSession)
	tcpSession.conn = conn
	tcpSession.writeQueue = make(chan []byte, writeQueueSize)
	go tcpSession.write()
	go tcpSession.read()
	return tcpSession
}

func (tcpSession *TcpSession) read() {
	//...

}

func (tcpSession *TcpSession) write() {
	for b := range tcpSession.writeQueue {
		if b == nil {
			break
		}
		_, err := tcpSession.conn.Write(b)
		if err != nil {
			logrus.Debug(err)
			break
		}
	}
}

func (tcpSession *TcpSession) Send(b []byte) {
	if len(tcpSession.writeQueue) == cap(tcpSession.writeQueue) {
		logrus.Debugf("close conn : write channel full !")
		tcpSession.doDestroy()
		return
	}
	tcpSession.writeQueue <- b
}

func (tcpSession *TcpSession) doDestroy() {
	tcpSession.conn.(*net.TCPConn).SetLinger(0)
	tcpSession.conn.Close()

	if !tcpSession.closeFlag {
		close(tcpSession.writeQueue)
		tcpSession.closeFlag = true
	}
}

func (tcpSession *TcpSession) RemoteAddr() net.Addr {
	return tcpSession.conn.RemoteAddr()
}
func (tcpSession *TcpSession) LocalAddr() net.Addr {
	return tcpSession.conn.LocalAddr()
}
